from fastapi import FastAPI, Request
from enum import Enum
import logging
from logging.config import dictConfig


from .config import settings, Environment
import dependencies.asgi_correlation_id.asgi_correlation_id as asgi_correlation_id

from uvicorn.config import LOGGING_CONFIG

class LOG_LEVEL(Enum):
    DEBUG = 'DEBUG',
    INFO = 'INFO',
    WARNING = 'WARNING',
    ERROR = 'ERROR'

__format = {
                'class': 'logging.Formatter',
                'datefmt': '%Y/%m/%d %H:%M:%S',
                'format': '%(levelname)s:\t\b%(asctime)s.%(msecs)03d [%(correlation_id)s] [%(filename)s:%(funcName)s:%(lineno)d] - %(message)s',
            }

__filters = {  # correlation ID filter must be added here to make the %(correlation_id)s formatter work
                'correlation_id': {
                    '()': 'dependencies.asgi_correlation_id.asgi_correlation_id.CorrelationIdFilter',
                    'uuid_length': 8 if settings.ENV == Environment.LOCAL else 32,
                    'default_value': '-',
                },
            }
LOGGING_CONFIG['filters'] = __filters
LOGGING_CONFIG["handlers"]["access"]["filters"] = ['correlation_id']
LOGGING_CONFIG["formatters"]["access"] = __format
    

def init_logging(level: LOG_LEVEL = LOG_LEVEL.DEBUG):

    def __init_logging():
        dictConfig(
            {
                'version': 1,
                'disable_existing_loggers': False,
                'filters': __filters,
                'formatters': {
                    'console': __format,
                },
                'handlers': {
                    'console': {
                        'class': 'logging.StreamHandler',
                        'filters': ['correlation_id'],
                        'formatter': 'console',
                    },
                },
                'loggers': {
                    # project logger
                    'app': {'handlers': ['console'], 'level': level.name, 'propagate': True},
                    # third-party package loggers
                    # 'databases': {'handlers': ['console'], 'level': 'WARNING'},
                    # 'httpx': {'handlers': ['console'], 'level': 'INFO'},
                    'asgi_correlation_id': {'handlers': ['console'], 'level': 'WARNING'},

                }
            }
        )
    return __init_logging

logger = logging.getLogger('app')
 
# from loguru import logger
# from starlette.responses import JSONResponse
# from starlette.middleware.base import BaseHTTPMiddleware

# format="{time:YYYY-MM-DD HH:mm:ss.ms} 6666 [{extra[request_id]}] | {level} | {module}.{function}:{line} : {message}"

# logger.add(
#     "log.log",
#     format=format,
# )
# logger.add(
#     sys.stdout,
#     format=format,
#     colorize=True
# )

# class LoggerMiddleware(BaseHTTPMiddleware):
#     async def dispatch(self, request: Request, call_next):
#         start_time = time.time()        
        
#         request_id = str(uuid.uuid4())
#         with logger.contextualize(request_id=request_id):
#             logger.info("Request started")
#             start_time = time.time()
#             try:
#                 response = await call_next(request)
#                 return response
    
#             except Exception as ex:
#                 logger.error(f"Request failed: {ex}")
#                 return JSONResponse(content={"success": False}, status_code=500)
    
#             finally:
#                 process_time = time.time() - start_time
#                 logger.info(f"Request ended, process_time = {process_time}")
